package com.example.springcloudwinter.token;

import io.jsonwebtoken.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class JWTAuthenticationToken implements AuthenticationToken{

    private final Logger logger = LogManager.getLogger(getClass());
    @Override
    public String getToken(Map<String, Object> payload) {
        return build(payload);
    }

    @Override
    public boolean verify(String token) {
        try {
            return Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody().getExpiration().after(new Date());
        }catch (Exception e){
            logger.info(e.getMessage());
            return false;
        }
    }

    @Override
    public String getBody(String token, String key) {
        return Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody().get(key,String.class);
    }


    public String build(Map<String,Object> payload){
        return Jwts.builder()
                .setHeader(jwtProperties.getHeader())
                .setClaims(payload)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+jwtProperties.getAccessTokenExpiration()*1000))
                .setSubject(jwtProperties.getSubject())
                .setIssuer(jwtProperties.getJwtIss())
                .signWith(jwtProperties.getSignatureAlgorithm(), jwtProperties.getSecret())
                .compact();
    }

    private final JWTPropertiesInterface jwtProperties;

    public JWTAuthenticationToken(JWTPropertiesInterface jwtProperties){
        this.jwtProperties=jwtProperties;
    }

}
